/*
 * tw_time.c
 *
 *  Created on: 2015-5-15
 *      Author: likui
 */

#include "tw_timer.h"
#include "error.h"

#include <stdlib.h>

/**
 * @brief 创建一个定时器结构并将其初始化为默认值。内存空间为动态分配，需要调用tw_timer_destroy释放
 * @return 返回一个定时器结构指针
 */
tw_timer_t *tw_timer_create(int rotation, int time_slot)
{
#ifndef NDEBUG
	error_msg("    timer_create rot = %d, slot = %d", rotation, time_slot);
#endif
	tw_timer_t *timer;

	timer = (tw_timer_t *)malloc(sizeof(tw_timer_t));
	if (timer == NULL) {
		error_msg("malloc error");
		return NULL;
	}

	timer->rotation = rotation;
	timer->time_slot = time_slot;
	timer->cb_func = NULL;
	timer->http_conn = NULL;
	timer->prev = NULL;
	timer->next = NULL;

	return timer;
}

/**
 * @brief 销毁一个定时器结构
 * @param 定时器结构指针的指针
 */
void tw_timer_destroy(tw_timer_t **timer)
{
	free(*timer);
	*timer = NULL;
}

/**
 * @brief 销毁一个定时器结构链表，从参数timer处开始销毁
 * @param head 指向定时器结构指针的指针
 */
void tw_timer_list_destroy(tw_timer_t **head)
{
	tw_timer_t *tmp = (*head);

	while (tmp) {
		(*head) = (*head)->next;
		tw_timer_destroy(&tmp);
		tmp = *head;
	}
	// 循环结束是，*head为NULL值
}

/**
 *@brief 添加一个定时器到链表的首部
 *@param head 指向链表首部指针的指针
 *@param timer 指向一个定时器的指针
 */
void tw_timer_list_add(tw_timer_t **head, tw_timer_t *timer)
{
	if (timer == NULL) {
		return;
	}

	if (*head == NULL) {			// 头节点为空

		(*head) = timer;
	} else {						// 头节点不为空
		timer->next = (*head);
		(*head)->prev = timer;
		(*head) = timer;
	}
}

/**
 * @brief 从链表中删除一个定时器结点
 * @param head
 * @param timer
 * @return 返回被删除结点的下一个结点
 */
tw_timer_t *tw_timer_list_del(tw_timer_t **head, tw_timer_t *timer)
{
#ifndef NDEBUG
		error_msg("        del_from_list: slot = %d", timer->time_slot);
#endif
	tw_timer_t *tmp;

	if (*head == timer) {				// 需要删除的结点为头结点
		tmp = *head;
		*head = (*head)->next;
		if (*head != NULL) {
			(*head)->prev = NULL;
		}
		tw_timer_destroy(&tmp);

		return (*head);
	} else {							// 需要删除的结点非头结点
		tmp = timer->next;
		timer->prev->next = timer->next;
		if (timer->next) {
			timer->next->prev = timer->prev;
		}
		tw_timer_destroy(&timer);

		return tmp;
	}
}
